import React, { useMemo } from 'react';
import { message, Spin, Tabs } from 'antd';
import { PageContainer } from '@/molecules';
import { withRouter, router } from 'umi';
import PositionTabContent from '@/pages/Organization/EmployeeManage/EmployeeDetail/components/PositionTabContent';
import ScheduleTabContent from '@/pages/Organization/EmployeeManage/EmployeeDetail/components/ScheduleTabContent';
import MaterialsTabContent from '@/pages/Organization/EmployeeManage/EmployeeDetail/components/MaterialsTabContent';
import CourseTabContent from '@/pages/Organization/EmployeeManage/EmployeeDetail/components/CourseTabContent';
import AssetsTabContent from '@/pages/Organization/EmployeeManage/EmployeeDetail/components/AssetsTabContent';
import PersonalTabContent from '@/pages/Organization/EmployeeManage/EmployeeDetail/components/PersonalTabContent';
import ContactTabContent from '@/pages/Organization/EmployeeManage/EmployeeDetail/components/ContactTabContent';
import SalaryTabContent from '@/pages/Organization/EmployeeManage/EmployeeDetail/components/SalaryTabContent';
import RecruitmentTabContent from '@/pages/Organization/EmployeeManage/EmployeeDetail/components/RecruitmentTabContent';
import authHelper from '@/utils/auth/helper';
import {
    checkHasEmployeePermission,
    getEmployeeInfoAndAds,
    getPersonalDoc,
    queryEmployeeArchiveHead
} from '@/pages/Organization/EmployeeManage/services';
import { defaultFormatResult, useRequest } from '@/hooks';
import { eventTrack } from '@/utils/track';
import EmployeeCard from '../components/EmployeeCard';
import EmployeeDetailContext from './store/context';
import styles from './index.less';

// 选项卡类型
const TAB_TYPES = [
    'position',
    'schedule',
    'course',
    'personal',
    'contact',
    'assets',
    'salary',
    'materials',
    'recruitment'
];

/**
 * 员工详情
 * /personal/myInfo
 * /office/personnelManagement/organization/employeeList/detail
 */
const EmployeeDetail = ({ location }) => {
    const userInfo = JSON.parse(localStorage.getItem('user'));
    const { employeeCode: queryEmployeeCode, dutyCode: queryDutyCode, tab } = location.query;
    const isPersonalPage = location.pathname.includes('personal/myInfo') || userInfo.employeeCode === queryEmployeeCode; // 是否是个人档案类型页面，或者登录账户本人

    const employeeCode = useMemo(() => {
        if (!isPersonalPage) {
            return queryEmployeeCode;
        }
        // 如果 url 的 employeeCode 参数为空, 就取当前用户的数据
        if (!employeeCode) {
            return userInfo.employeeCode;
        }
        return null;
    }, [isPersonalPage, queryEmployeeCode, userInfo?.employeeCode]);

    // 校验是否有目标用户访问权限
    const { data: hasEmployeePermission, loading: hasEmployeePermissionLoading } = useRequest(
        () => checkHasEmployeePermission(queryEmployeeCode),
        {
            cacheKey: `employee-tab-auth-${queryEmployeeCode}`,
            refreshDeps: [queryEmployeeCode, queryDutyCode],
            ready: !isPersonalPage,
            ...defaultFormatResult
        }
    );
    // 获取员工信息
    const { data: employeeInfo, loading: employeeInfoLoading, refresh: refreshEmployeeInfo } = useRequest(
        () => getEmployeeInfoAndAds({ employeeCode }),
        {
            cacheKey: `employee-info-${queryEmployeeCode}`,
            refreshDeps: [queryEmployeeCode],
            ready: employeeCode,
            ...defaultFormatResult
        }
    );

    // 获取新加坡的身份类型
    const { data: singaporeIdType, refresh: refreshSingaporeIdType } = useRequest(
        () => getPersonalDoc({ employeeCode }),
        {
            cacheKey: `employee-personal-${employeeCode}`,
            refreshDeps: [employeeCode],
            formatResult: res => {
                if (res) {
                    const { code, data, msg } = res;
                    if (code === 10000) {
                        const targetEmployeeExtendInfoItem = data.employeeExtendInfoList.find(
                            item => item.fieldCode === 'singaporeIdType'
                        );
                        if (targetEmployeeExtendInfoItem) {
                            return targetEmployeeExtendInfoItem?.fieldValue;
                        }
                        return undefined;
                    }
                    message.error(msg);
                }
                return undefined;
            }
        }
    );

    // 选项卡的权限列表
    const tabContentAuthMap = useMemo(() => {
        const checkTabAuth = authCode => {
            if (isPersonalPage) {
                // 部分选项卡, 即便是查看个人档案也要判断权限
                return authHelper.checkCode(authCode);
            }
            return hasEmployeePermission === true && authHelper.checkCode(authCode);
        };
        return {
            positionTabAuth: isPersonalPage || authHelper.checkCode('office:orgs:employee:detail:getJob'),
            scheduleTabAuth: isPersonalPage || checkTabAuth('office:orgs:employee:detail:getSchedule'),
            courseTabAuth: isPersonalPage || checkTabAuth('office:orgs:employee:detail:getCourse'),
            personalTabAuth: isPersonalPage || checkTabAuth('office:orgs:employee:detail:getPersonal'),
            contactTabAuth: isPersonalPage || checkTabAuth('office:orgs:employee:detail:getContact'),
            assetsTabAuth: isPersonalPage || checkTabAuth('office:orgs:employee:detail:getAsset'),
            salaryTabAuth: isPersonalPage || checkTabAuth('office:orgs:employee:detail:getSalary'),
            materialsTabAuth: isPersonalPage || checkTabAuth('office:orgs:employee:detail:getResource'),
            recruitmentTabAuth: isPersonalPage || checkTabAuth('office:orgs:employee:detail:getRecruitment')
        };
    }, [hasEmployeePermission, isPersonalPage]);

    const dutyCode = useMemo(() => {
        if (!isPersonalPage) {
            return queryDutyCode;
        }
        // 如果 url 的 employeeCode 参数为空, 就取当前用户的数据
        if (!employeeCode) {
            return userInfo.firstOrgInfo.dutyCode;
        }
        return queryDutyCode || userInfo.firstOrgInfo.dutyCode;
    }, [employeeCode, isPersonalPage, queryDutyCode, userInfo.firstOrgInfo.dutyCode]);

    // 查询员工档案头部信息，查看员工的是否已离职，进而判断是否隐藏一些按钮
    const { data: employeeInfoData, loading: employeeInfoLoading2 } = useRequest(
        () => queryEmployeeArchiveHead({ employeeCode, dutyCode }),
        {
            cacheKey: `employee-info-${employeeCode}-${dutyCode}`,
            refreshDeps: [employeeCode, dutyCode],
            ready: employeeCode,
            ...defaultFormatResult
        }
    );

    // 默认选项卡
    const activeKey = useMemo(() => {
        const tabAuth = tabContentAuthMap[`${tab}TabAuth`];
        if (tab && TAB_TYPES.includes(tab) && tabAuth) {
            return tab;
        }
        // 定位第一个有权限的选项卡
        const firstHasAuthTabContent = Object.keys(tabContentAuthMap)?.filter(key => !!tabContentAuthMap[key])?.[0];
        return firstHasAuthTabContent ? firstHasAuthTabContent.replace('TabAuth', '') : TAB_TYPES[0];
    }, [tab, tabContentAuthMap]);

    // 切换选项卡
    const handleTabChange = tabKey => {
        history.push({ pathname: location.pathname, query: { ...location.query, tab: tabKey } });
    };

    // render
    return (
        <PageContainer>
            <EmployeeDetailContext.Provider
                value={{
                    employeeCode,
                    employeeInfo,
                    isPersonalPage,
                    refreshEmployeeInfo,
                    singaporeIdType,
                    refreshSingaporeIdType
                }}
            >
                {/* 员工基础信息 */}
                <EmployeeCard
                    employeeCode={employeeCode}
                    dutyCode={dutyCode}
                    isPersonalPage={isPersonalPage}
                    currentTabKey={tab}
                    hasEmployeePermission={hasEmployeePermission}
                    style={{ margin: '8px 8px 20px' }}
                />
                {/* 选项卡 */}
                <Spin spinning={hasEmployeePermissionLoading || employeeInfoLoading || employeeInfoLoading2}>
                    <Tabs type="card" activeKey={activeKey} onChange={handleTabChange}>
                        {tabContentAuthMap.positionTabAuth && (
                            <Tabs.TabPane
                                tab={
                                    <div
                                        className={styles.tabPaneLabel}
                                        onClick={() => {
                                            // 埋点
                                            eventTrack({
                                                eventName: 'personal_my_info_position_click',
                                                pageName: 'personal_my_info'
                                            });
                                        }}
                                    >
                                        在职信息
                                    </div>
                                }
                                key="position"
                            >
                                <PositionTabContent employeeCode={employeeCode} dutyCode={dutyCode} />
                            </Tabs.TabPane>
                        )}
                        {tabContentAuthMap.scheduleTabAuth && (
                            <Tabs.TabPane
                                tab={
                                    <div
                                        className={styles.tabPaneLabel}
                                        onClick={() => {
                                            // 埋点
                                            eventTrack({
                                                eventName: 'personal_my_info_schedule_click',
                                                pageName: 'personal_my_info'
                                            });
                                        }}
                                    >
                                        工作日程
                                    </div>
                                }
                                key="schedule"
                            >
                                <ScheduleTabContent employeeCode={employeeCode} />
                            </Tabs.TabPane>
                        )}
                        {tabContentAuthMap.courseTabAuth && (
                            <Tabs.TabPane
                                tab={
                                    <div
                                        className={styles.tabPaneLabel}
                                        onClick={() => {
                                            // 埋点
                                            eventTrack({
                                                eventName: 'personal_my_info_course_click',
                                                pageName: 'personal_my_info'
                                            });
                                        }}
                                    >
                                        微微历程
                                    </div>
                                }
                                key="course"
                            >
                                <CourseTabContent employeeCode={employeeCode} />
                            </Tabs.TabPane>
                        )}
                        {tabContentAuthMap.personalTabAuth && (
                            <Tabs.TabPane
                                tab={
                                    <div
                                        className={styles.tabPaneLabel}
                                        onClick={() => {
                                            // 埋点
                                            eventTrack({
                                                eventName: 'personal_my_info_personal_click',
                                                pageName: 'personal_my_info'
                                            });
                                        }}
                                    >
                                        个人信息
                                    </div>
                                }
                                key="personal"
                            >
                                <PersonalTabContent
                                    employeeCode={employeeCode}
                                    isPersonalPage={isPersonalPage}
                                    employeeInfoData={employeeInfoData}
                                />
                            </Tabs.TabPane>
                        )}
                        {tabContentAuthMap.contactTabAuth && (
                            <Tabs.TabPane
                                tab={
                                    <div
                                        className={styles.tabPaneLabel}
                                        onClick={() => {
                                            // 埋点
                                            eventTrack({
                                                eventName: 'personal_my_info_contact_click',
                                                pageName: 'personal_my_info'
                                            });
                                        }}
                                    >
                                        联系信息
                                    </div>
                                }
                                key="contact"
                            >
                                <ContactTabContent
                                    employeeCode={employeeCode}
                                    isPersonalPage={isPersonalPage}
                                    employeeInfoData={employeeInfoData}
                                />
                            </Tabs.TabPane>
                        )}
                        {tabContentAuthMap.assetsTabAuth && (
                            <Tabs.TabPane
                                tab={
                                    <div
                                        className={styles.tabPaneLabel}
                                        onClick={() => {
                                            // 埋点
                                            eventTrack({
                                                eventName: 'personal_my_info_assets_click',
                                                pageName: 'personal_my_info'
                                            });
                                        }}
                                    >
                                        资产信息
                                    </div>
                                }
                                key="assets"
                            >
                                <AssetsTabContent employeeCode={employeeCode} />
                            </Tabs.TabPane>
                        )}
                        {tabContentAuthMap.salaryTabAuth && (
                            <Tabs.TabPane
                                tab={
                                    <div
                                        className={styles.tabPaneLabel}
                                        onClick={() => {
                                            // 埋点
                                            eventTrack({
                                                eventName: 'personal_my_info_salary_click',
                                                pageName: 'personal_my_info'
                                            });
                                        }}
                                    >
                                        工资社保
                                    </div>
                                }
                                key="salary"
                            >
                                <SalaryTabContent
                                    employeeCode={employeeCode}
                                    isPersonalPage={isPersonalPage}
                                    employeeInfoData={employeeInfoData}
                                />
                            </Tabs.TabPane>
                        )}
                        {tabContentAuthMap.materialsTabAuth && (
                            <Tabs.TabPane
                                tab={
                                    <div
                                        className={styles.tabPaneLabel}
                                        onClick={() => {
                                            // 埋点
                                            eventTrack({
                                                eventName: 'personal_my_info_materials_click',
                                                pageName: 'personal_my_info'
                                            });
                                        }}
                                    >
                                        材料附件
                                    </div>
                                }
                                key="materials"
                            >
                                <MaterialsTabContent
                                    employeeCode={employeeCode}
                                    isPersonalPage={isPersonalPage}
                                    employeeInfoData={employeeInfoData}
                                />
                            </Tabs.TabPane>
                        )}
                        {tabContentAuthMap.recruitmentTabAuth && (
                            <Tabs.TabPane
                                tab={
                                    <div
                                        className={styles.tabPaneLabel}
                                        onClick={() => {
                                            // 埋点
                                            eventTrack({
                                                eventName: 'personal_my_info_recruitment_click',
                                                pageName: 'personal_my_info'
                                            });
                                        }}
                                    >
                                        应聘记录
                                    </div>
                                }
                                key="recruitment"
                            >
                                <RecruitmentTabContent employeeCode={employeeCode} />
                            </Tabs.TabPane>
                        )}
                    </Tabs>
                </Spin>
            </EmployeeDetailContext.Provider>
        </PageContainer>
    );
};

export default withRouter(EmployeeDetail);
